package com.thinkgsp.webapp.controller.base;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thinkgsp.jxc.model.Dept;
import com.thinkgsp.jxc.model.InventoryAdd;
import com.thinkgsp.sys.model.SysUser;
import com.thinkgsp.sys.service.*;
import com.thinkgsp.webapp.controller.BaseController;
import com.thinkgsp.webapp.util.ExtReturn;
@Controller
@RequestMapping(value = "/sys")
public class UserController extends BaseController{

	private SysUserService sysUserService=null;
	@Autowired
	private PasswordEncoder passwordEncoder;
	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}
	
	@Autowired
	public void setSysUserService(SysUserService sysUserService) {
		this.sysUserService = sysUserService;
	}		
	@RequestMapping(value = "/users.do")
	@ResponseBody
	public Object showForm(HttpServletRequest request,
			HttpServletResponse response) {
		String userIdStr = request.getParameter("userId");
		if(!StringUtils.isBlank(userIdStr)){
			Integer userId=Integer.decode(userIdStr);
			SysUser user= sysUserService.getUser(userId);
			List<SysUser> us=new ArrayList();
			us.add(user);
			return us;
		}else{
			List<SysUser> users = sysUserService.getUsers();
			return users;
		}
	}
	@RequestMapping(value = "/adduser.do")
	@ResponseBody
	public Object add(Model model ,@RequestBody SysUser user) {
		try {
			this.sysUserService.saveUser(user);
			return new ExtReturn(true,"添加用户成功");
		} catch (Exception e) {
			return new ExtReturn(false,"添加用户失败",e.getMessage());
		}
	}

	@RequestMapping(value = "/upduser.do")
	@ResponseBody
	public Object update(Model model ,@RequestBody SysUser user) {
		try {
			this.sysUserService.saveUser(user);
			return new ExtReturn(true,"修改用户成功");
		} catch (Exception e) {
			return new ExtReturn(false,"修改用户失败",e.getMessage());
		}
	}
	@RequestMapping(value = "/upduserpass.do")
	@ResponseBody
	public Object updatepass(HttpServletRequest request,
			HttpServletResponse response) {
		String userIdStr = request.getParameter("userId");
		String oldPass = request.getParameter("oldPassWord");
		String newPass = request.getParameter("newPassWord");
		
		if(StringUtils.isBlank(newPass)){
			return new ExtReturn(false,"修改用户密码失败","密码不能为空");
		}
		
		try {
			Integer userId=Integer.decode(userIdStr);
			SysUser user=this.sysUserService.getUser(userId);
			String epass=passwordEncoder.encodePassword(oldPass,null);
			if(!epass.equals(user.getPassword())){
				return new ExtReturn(false,"修改用户密码失败","原密码不正确");
			}
			if(newPass.equals(user.getPassword())){
				return new ExtReturn(false,"修改用户密码","密码未变更");
			}
			user.setPassword(newPass);
			this.sysUserService.saveUser(user);
			return new ExtReturn(true,"修改用户密码成功");
		} catch (Exception e) {
			return new ExtReturn(false,"修改用户密码失败",e.getMessage());
		}
	}
	
	@RequestMapping(value = "/deluserrole.do")
	@ResponseBody
	public Object deluserrole(HttpServletRequest request,
			HttpServletResponse response) {
		String userIdStr = request.getParameter("userId");
		String roleIdStr = request.getParameter("roleId");
		try {
			if(!StringUtils.isBlank(userIdStr) && !StringUtils.isBlank(roleIdStr) ){
				Integer userId=Integer.decode(userIdStr);
				if(userId==1){
					return new ExtReturn(false,"系统超级用户不能删除角色");
				}
				Integer roleId=Integer.decode(roleIdStr);
				this.sysUserService.deleteRole(userId, roleId);
			}else{
				return new ExtReturn(false,"未获取用户ID");
			}
			return new ExtReturn(true,"删除用户角色成功");
		} catch (Exception e) {
			return new ExtReturn(false,"删除用户角色失败",e.getMessage());
		}
	}
	@RequestMapping(value = "/adduserrole.do")
	@ResponseBody
	public Object adduserrole(HttpServletRequest request,
			HttpServletResponse response) {
		String userIdStr = request.getParameter("userId");
		String roleIdStr = request.getParameter("roleId");
		String[] ids=roleIdStr.split(",");
		try {
			if(!StringUtils.isBlank(userIdStr) && ids.length>0){
				Integer userId=Integer.decode(userIdStr);
				for (String id : ids) {
					Integer roleId=Integer.decode(id);
					this.sysUserService.addRole(userId, roleId);
				}
				return new ExtReturn(true,"添加用户角色成功");
			}
			else{
				return new ExtReturn(false,"未获取用户ID");
			}
				
			
		} catch (Exception e) {
			return new ExtReturn(false,"添加用户角色失败",e.getMessage());
		}
	}
	
	@RequestMapping(value = "/deluser.do")
	@ResponseBody
	public Object delete(HttpServletRequest request,
			HttpServletResponse response) {
		String userIdStr = request.getParameter("userId");
		try {
			if(!StringUtils.isBlank(userIdStr)){
				Integer userId=Integer.decode(userIdStr);
				if(userId==1){
					return new ExtReturn(false,"系统超级用户不能删除");
				}
				this.sysUserService.removeUser(userId);
				
				return new ExtReturn(true,"删除用户成功");
			}else{
				return new ExtReturn(false,"未获取用户ID");
			}	
			
		} catch (Exception e) {
			return new ExtReturn(false,"删除用户失败",e.getMessage());
		}
	}
	
	@RequestMapping(value = "/adduserinv.do")
	@ResponseBody
	public Object adduserinv(HttpServletRequest request,
			HttpServletResponse response) {
		String userIdStr = request.getParameter("userId");
		String invAddIdStr = request.getParameter("invAddId");
		try {
			if(!StringUtils.isBlank(userIdStr) && !StringUtils.isBlank(invAddIdStr) ){
				Integer userId=Integer.decode(userIdStr);
				Integer invAddId=Integer.decode(invAddIdStr);
				this.sysUserService.addUserInvAdd(userId, invAddId);
				return new ExtReturn(true,"添加用户存货地址成功");
			}else{
				return new ExtReturn(false,"未获取用户ID或存货地址ID");
			}	
		} catch (Exception e) {
			return new ExtReturn(false,"添加用户存货地址失败",e.getMessage());
		}
	}
	@RequestMapping(value = "/upduserinv.do")
	@ResponseBody
	public Object upduserinv(HttpServletRequest request,
			HttpServletResponse response) {
		String userIdStr = request.getParameter("userId");
		String invAddIdsStr = request.getParameter("invAddIds");
		try {
			if(!StringUtils.isBlank(userIdStr) && !StringUtils.isBlank(invAddIdsStr) ){
				String[] ids=invAddIdsStr.split(",");
				Integer userId=Integer.decode(userIdStr);
				SysUser user=this.sysUserService.getUser(userId);
				List<InventoryAdd> lst=user.getInvadds();
				List<Integer> userids= new ArrayList<Integer>();
				for (int i = 0; i < lst.size(); i++) {
					userids.add(lst.get(i).getId());
				}
				List<Integer> newids= new ArrayList<Integer>();
				for (String sid : ids) {
					
					Integer invAddId=Integer.decode(sid);
					newids.add(invAddId);
				}
				for (Integer invAddId : newids) {
					if(userids.contains(invAddId)) continue;
					this.sysUserService.addUserInvAdd(userId, invAddId);
				}
				for (Integer invAddId : userids) {
					if(!newids.contains(invAddId)){
						this.sysUserService.delelteUserInvAdd(userId, invAddId);
					}
				}
				user=this.sysUserService.getUser(userId);
				lst=user.getInvadds();
				Boolean flag=false;
				for (InventoryAdd iv : lst) {
					if(iv.isDefaultInvAdd()){
						flag=true;
						break;
					}
				}
				if(!flag && lst.size()>0){
					this.sysUserService.setDefaultInvAdd(userId,lst.get(0).getId());
				}
				return new ExtReturn(true,"修改用户存货地址成功");
			}else{
				return new ExtReturn(false,"未获取用户ID或存货地址ID");
			}	
		} catch (Exception e) {
			return new ExtReturn(false,"修改用户存货地址失败",e.getMessage());
		}
	}
	
	@RequestMapping(value = "/upduserinvdef.do")
	@ResponseBody
	public Object upduserinvdef(HttpServletRequest request,
			HttpServletResponse response) {
		String userIdStr = request.getParameter("userId");
		String invAddIdStr = request.getParameter("invAddId");
		try {
			if(!StringUtils.isBlank(userIdStr) && !StringUtils.isBlank(invAddIdStr) ){
				Integer userId=Integer.decode(userIdStr);
				Integer invAddId=Integer.decode(invAddIdStr);
				SysUser user=this.sysUserService.getUser(userId);
				List<InventoryAdd> lst=user.getInvadds();
				for (InventoryAdd inventoryAdd : lst) {
					if(inventoryAdd.getId()==invAddId){
						this.sysUserService.setDefaultInvAdd(userId, invAddId);
						return new ExtReturn(true,"设置默认存货地址成功");
					}
				}
				return new ExtReturn(false,"请先添加该存货地址后再设置为默认");
				
			}else{
				return new ExtReturn(false,"未获取用户ID或存货地址ID");
			}	
		} catch (Exception e) {
			return new ExtReturn(false,"设置默认存货地址失败",e.getMessage());
		}
	}
	@RequestMapping(value = "/deluserinv.do")
	@ResponseBody
	public Object deluserinv(HttpServletRequest request,
			HttpServletResponse response) {
		String userIdStr = request.getParameter("userId");
		String invAddIdStr = request.getParameter("invAddId");
		try {
			if(!StringUtils.isBlank(userIdStr) && !StringUtils.isBlank(invAddIdStr) ){
				Integer userId=Integer.decode(userIdStr);
				Integer invAddId=Integer.decode(invAddIdStr);
				this.sysUserService.delelteUserInvAdd(userId, invAddId);
				return new ExtReturn(true,"删除用户存货地址成功");
			}else{
				return new ExtReturn(false,"未获取用户ID或存货地址ID");
			}
		} catch (Exception e) {
			return new ExtReturn(false,"删除用户存货地址失败",e.getMessage());
		}
	}
	
	@RequestMapping("/invadds.do")
    @ResponseBody
    public Object invadds(HttpServletRequest request,
			HttpServletResponse response){
		SysUser user =null;
		String idstr=request.getParameter("userId");
		//如果参数传入UserId则取用户的 存货地址列表,没有则取当前登录用户的
		if(!StringUtils.isBlank(idstr)){
			Integer userId=Integer.decode(idstr);
			user=this.sysUserService.getUser(userId);
		}else{
			user = (SysUser) SecurityContextHolder.getContext()
				    .getAuthentication()
				    .getPrincipal();
		}
		
		//Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) user.getAuthorities();
		List<InventoryAdd> lst=user.getInvadds();
		
		return lst;
	}
	
	@RequestMapping("/getDepts.do")
    @ResponseBody
    public Object getDepts(HttpServletRequest request,
			HttpServletResponse response){
		SysUser user =null;
		String idstr=request.getParameter("userId");
		//如果参数传入UserId则取用户的 存货地址列表,没有则取当前登录用户的
		if(!StringUtils.isBlank(idstr)){
			Integer userId=Integer.decode(idstr);
			user=this.sysUserService.getUser(userId);
		}else{
			user = (SysUser) SecurityContextHolder.getContext()
				    .getAuthentication()
				    .getPrincipal();
		}
		
		//Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) user.getAuthorities();
		List<Dept> lst=user.getDepts();
		
		return lst;
	}
	
	@RequestMapping(value = "/updDefDept.do")
	@ResponseBody
	public Object updDefDept(@RequestParam Integer userId,@RequestParam Integer deptId) {
		try {
				SysUser user=this.sysUserService.getUser(userId);
				List<Dept> lst=user.getDepts();
				for (Dept dept : lst) {
					if(dept.getDeptId()==deptId){
						this.sysUserService.setDefaultDept(userId, deptId);
						return new ExtReturn(true,"设置默认部门成功");
					}
				}
				return new ExtReturn(false,"请先添加部门后再设置为默认");	
		} catch (Exception e) {
			loger.error(e.getMessage());
			return new ExtReturn(false,"设置默认部门失败",e.getMessage());
		}
	}
	
	@RequestMapping(value = "/delUserDept.do")
	@ResponseBody
	public Object delUserDept(@RequestParam Integer userId,@RequestParam Integer deptId) {
		try {
			this.sysUserService.deleteUserDept(userId, deptId);
			return new ExtReturn(true,"删除用户所属部门成功");

		} catch (Exception e) {
			loger.error(e.getMessage());
			return new ExtReturn(false,"删除用户所属部门失败",e.getMessage());
		}
	}
	@RequestMapping(value = "/addUserdEPT.do")
	@ResponseBody
	public Object addUserDept(@RequestParam Integer userId,@RequestParam Integer deptId) {
		try {
			this.sysUserService.addUserDept(userId, deptId);
			return new ExtReturn(true,"添加用户所属部门成功");	
		} catch (Exception e) {
			loger.error(e.getMessage());
			return new ExtReturn(false,"添加用户所属部门失败",e.getMessage());
		}
	}
	
	@RequestMapping(value = "/updUserDept.do")
	@ResponseBody
	public Object updUserDept(HttpServletRequest request,
			HttpServletResponse response) {
		String userIdStr = request.getParameter("userId");
		String deptIdsStr = request.getParameter("deptIds");
		try {
			if(!StringUtils.isBlank(userIdStr) && !StringUtils.isBlank(deptIdsStr) ){
				String[] ids=deptIdsStr.split(",");
				Integer userId=Integer.decode(userIdStr);
				SysUser user=this.sysUserService.getUser(userId);
				List<Dept> lst=user.getDepts();
				List<Integer> userids= new ArrayList<Integer>();
				for (int i = 0; i < lst.size(); i++) {
					userids.add(lst.get(i).getDeptId());
				}
				List<Integer> newids= new ArrayList<Integer>();
				for (String sid : ids) {
					
					Integer deptId=Integer.decode(sid);
					newids.add(deptId);
				}
				for (Integer deptId : newids) {
					if(userids.contains(deptId)) continue;
					this.sysUserService.addUserDept(userId, deptId);
				}
				for (Integer deptId : userids) {
					if(!newids.contains(deptId)){
						this.sysUserService.deleteUserDept(userId, deptId);
					}
				}
				user=this.sysUserService.getUser(userId);
				lst=user.getDepts();
				Boolean flag=false;
				for (Dept iv : lst) {
					if(iv.isDefaultDept()){
						flag=true;
						break;
					}
				}
				if(!flag && lst.size()>0){
					this.sysUserService.setDefaultDept(userId,lst.get(0).getDeptId());
				}
				return new ExtReturn(true,"修改用户所属部门成功");
			}else{
				if(!StringUtils.isBlank(userIdStr)){
					Integer userId=Integer.decode(userIdStr);
					SysUser user=this.sysUserService.getUser(userId);
					List<Dept> lst=user.getDepts();
					for (int i = 0; i < lst.size(); i++) {
						this.sysUserService.deleteUserDept(userId, lst.get(i).getDeptId());
					}
					return new ExtReturn(true,"修改用户所属部门成功");
				}else{
					return new ExtReturn(false,"未获取用户ID或部门ID");
				}
			}	
		} catch (Exception e) {
			return new ExtReturn(false,"修改用户所属部门失败",e.getMessage());
		}
	}
}
